<template>
	<view class="u-p-20">
		<view class="u-p-30">
			<u-form :model="form" ref="uForm" label-width='140'>
				<u-form-item label="旧密码" prop="oldPassword">
					<u-input v-model="form.oldPassword" type='password' />
				</u-form-item>
				<u-form-item label="新密码" prop="password">
					<u-input v-model="form.password" type='password' />
				</u-form-item>
				<u-form-item label="重复密码" prop="againPassword">
					<u-input v-model="form.againPassword" type='password' />
				</u-form-item>
			</u-form>
		</view>
		<u-button class='u-m-t-30' type="warning" @click="submit">确定</u-button>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		userUpdate
	} from '@/api/shop.js'
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState(['userInfo', 'login'])
		},
		data() {
			return {
				form: {
					oldPassword: '',
					password: '',
					againPassword: ''
				},
				rules: {
					oldPassword: [{
						min: 5,
						required: true,
						message: '密码不能少于5个字',
						trigger: ['change', 'blur']
					}],
					password: [{
						min: 5,
						required: true,
						message: '密码不能少于5个字',
						trigger: ['change', 'blur']
					}],
					againPassword: [{
						required: true,
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							return value == this.form.password;
						},
						message: '两次输入的密码不一致',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur']
					}]
				}
			};
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						userUpdate({
							JSESSIONID: uni.getStorageSync('sessionid'),
							id: this.userInfo.id,
							oldPassword: this.form.oldPassword,
							password: this.form.password
						}).then(res => {
							this.$refs.uToast.show({
								title: '修改成功',
								type: 'success',
								back: true
							})
						})
					} else {
						console.log('验证失败');
					}
				});
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	};
</script>
